<?php

/**
 * This is the model class for table "{{product}}".
 *
 * The followings are the available columns in table '{{product}}':
 * @property integer $zp_id
 * @property integer $zm_id
 * @property integer $zp_tao_id
 * @property integer $zp_taopro_id
 * @property integer $zb_id
 * @property integer $zp_type
 * @property integer $zca_id
 * @property integer $zar_id
 * @property string $zp_name
 * @property string $zp_seotitle
 * @property string $zp_seokey
 * @property string $zp_seodesc
 * @property string $zp_product_no
 * @property double $zp_price
 * @property double $zp_saleprice
 * @property double $zp_costprice
 * @property double $zp_fx_price
 * @property double $zp_fx_saleprice
 * @property integer $zp_inventory
 * @property integer $zp_sale_num
 * @property integer $zp_tax
 * @property integer $zp_weight
 * @property string $zp_units
 * @property string $zp_pic
 * @property string $zp_content
 * @property integer $zp_status
 * @property string $zp_nostatus
 * @property integer $zp_state
 * @property integer $zp_draft
 * @property integer $zp_new
 * @property integer $zp_point
 * @property string $zt_ids
 * @property integer $zp_hits
 * @property integer $zp_fav_num
 * @property integer $zp_commend
 * @property integer $zp_fenxiao
 * @property integer $zp_repair
 * @property integer $zp_guarantee
 * @property integer $ze_id
 * @property string $zp_exp_config
 * @property integer $zbl_id
 * @property integer $inputtime
 * @property integer $updatetime
 */
class Product extends CActiveRecord
{
	//商品货号 用于跟据货号查询产品
	public $pro_no;
	
	//商品自定义一级分类， 用于跟据自定义一级分类查询产品
	public $pro_cat_one;
	
	//行业分类
	public $catgory_id;
	
	//搜索类型
	public $search_type;
	
	//销量统计列表，最小销量
	public $min_sale_num ;
	
	//搜索内容
	public $search_content;
	
	//排序,1时间倒序，2销量倒序
	public $list_order;
	
	//价格区间
	public $price_level;
	
	//最小价格
	public $price_min;
	
	//最大价格
	public $price_max;
	
	//产品属性,用于筛选，数组
	public $att;
	
	//关键字查询
	public $keyword;
	
	//
	public $butPromotion = false;
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Product the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{product}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('zm_id, zp_tao_id, zp_taopro_id,zp_prodid, zb_id, zp_type, zca_id, zar_id, zp_inventory, zp_sale_num, zp_tax, zp_weight, zp_status, zp_state, zp_draft, zp_new, zp_point, zp_hits, zp_fav_num, zp_commend, zp_fenxiao, zp_repair, zp_guarantee, ze_id, zbl_id, inputtime, updatetime, zp_exp_status', 'numerical', 'integerOnly'=>true),
			array('zp_price, zp_saleprice, zp_costprice, zp_fx_price, zp_fx_saleprice,pro_cat_one,search_type,list_order,price_level,price_min,price_max', 'numerical'),
			array('zp_name,search_content,keyword,pro_no', 'length', 'max'=>255),
			//array('zp_seotitle', 'length', 'max'=>100),
			//array('zp_units', 'length', 'max'=>10),
			array('zp_content, zp_seokey, zp_exp_config, att', 'safe'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('zp_id, zm_id, zp_tao_id, zp_taopro_id, zb_id, zp_type, zca_id, zar_id, zp_name, zp_seotitle, zp_seokey, zp_seodesc, zp_product_no, zp_price, zp_saleprice, zp_costprice, zp_fx_price, zp_fx_saleprice, zp_inventory, zp_sale_num, zp_tax, zp_weight, zp_units, zp_pic, zp_content, zp_status, zp_nostatus, zp_state, zp_draft, zp_new, zp_point, zt_ids, zp_hits, zp_fav_num, zp_commend, zp_fenxiao, zp_repair, zp_guarantee, ze_id, zp_exp_config, zbl_id, inputtime, updatetime,zp_exp_status', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
				'member'=>array(self::BELONGS_TO,'Member','zm_id'),
				'attribute'=>array(self::HAS_MANY , 'ProAttribute', 'zp_id','on'=>'zpa_type=1' ),//读取产品属性 OK
				'standard'=>array(self::HAS_MANY , 'ProAttribute', 'zp_id','on'=>'zpa_type=2' ),//读取产品规格 OK
				'spec'=>array(self::HAS_MANY , 'ProAttribute', 'zp_id','on'=>'zpa_type=3' ),//读取产品规格库存 
				'price'=>array(self::HAS_MANY , 'ProSpe', 'zp_id'),//读取产品价格
				'proimg'=>array(self::HAS_MANY , 'ProImages', 'zp_id' ,'order'=>'zpg_id ASC'),//读取产品图片 OK
				'company'=>array(self::BELONGS_TO,'Company','zm_id'),//公司信息
				'cmpcat'=>array(self::MANY_MANY ,'CmpCat','zd_cmp_catlog(zp_id,zpc_id)'),//自定义分类  OK
				'procomment' =>array(self::HAS_MANY,'OrdComment','zp_id'),//读取产品评论
				'propoint' =>array(self::HAS_MANY,'ProPoint','zp_id'),//读取产品积分
				'services' =>array(self::BELONGS_TO,'Block','zbl_id'),
				'express' =>array(self::BELONGS_TO , 'Express', 'ze_id'),//运费模板
		);
	}
		
	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'zp_id' => '产品ID',
			'zm_id' => '会员ID',
			'zp_tao_id' => '淘宝类目Id',
			'pro_no'=>'货号',
			'zp_taopro_id' => '淘宝产品ID',
			'zb_id' => '品牌ID',
			'zp_type' => '销售模式',//1:零售,2:批发,3:零售+批发',
			'zca_id' => '行业分类ID',
			'zar_id' => '地域ID',
			'zp_name' => '产品标题',
			'zp_seotitle' => 'SEO标题',
			'zp_seokey' => 'SEOKEY',
			'zp_seodesc' => 'SEO描述',
			'zp_product_no' => '用户产品编号',
			'zp_price' => '产品价格',
			'zp_saleprice' => '产品销售价',
			'zp_costprice' => '产品成本价',
			'zp_fx_price' => '产品分销价',
			'zp_fx_saleprice' => '产品分销零售价',
			'zp_inventory' => '产品库存',
			'zp_sale_num' => '总销量',
			'zp_tax' => '是否含税',//1:不含税2:含税'
			'zp_weight' => '重量',
			'zp_units' => '单位',
			'zp_pic' => '产品默认图片',
			'zp_content' => '产品描述',
			'zp_status' => '状态',//1审核中,2通过,3未通过
			'zp_nostatus' => '未通过理由',
			'zp_state' => '是否上架',//1否2是
			'zp_draft' => '发布时间',
			'zp_new' => '是否新产品',//1否2是
			'zp_point' => '是否积分产品',//1否2是
			'zt_ids' => '关键词ID',
			'zp_hits' => '点击数',
			'zp_fav_num' => '收藏次数',
			'zp_commend' => '商铺产品推荐',//1否2是
			'zp_fenxiao' => '是否分销',//1否2是
			'zp_repair' => '是否保修',//1无2有
			'zp_guarantee' => '退换货保证',//1无2有
			'zp_exp_status'=>'运费模式',//1卖家包邮2运费模板
			'ze_id' => '运费模板ID',
			'zp_exp_config' => '独立运费模板',
			'zbl_id' => '售后服务模板',
			'inputtime' => '创建时间',
			'updatetime' => '修改时间',
			'pro_id' => '货号',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search($pageSize=5)
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;
		$criteria->join = "";
		//搜索类型搜索
		if(!empty($this->search_type)){
			if($this->search_content=='请输入关键字')
				$this->search_content = '';
			if($this->search_type==1){
				//产品名称
				$this->zp_name = $this->search_content;
			}elseif($this->search_type==2){
				//公司名称
				$criteria->join .= ' LEFT JOIN {{company}} c ON c.zm_id=t.zm_id ';
				$criteria->addCondition("c.zc_name like '%".$this->search_content."%'");
			}
		}
		
		
		if(empty($this->pro_cat_one)){
			$criteria->compare('zm_id',$this->zm_id);
		}
		$criteria->compare('zp_tao_id',$this->zp_tao_id);
		$criteria->compare('zp_taopro_id',$this->zp_taopro_id);
		$criteria->compare('zca_id',$this->zca_id);
		$criteria->compare('zp_type',$this->zp_type);
		$criteria->compare('zb_id',$this->zb_id);
		$criteria->compare('zar_id',$this->zar_id);
		$criteria->compare('zp_seotitle',$this->zp_seotitle,true);
		$criteria->compare('zp_seokey',$this->zp_seokey,true);
		$criteria->compare('zp_seodesc',$this->zp_seodesc,true);
		$criteria->compare('zp_product_no',$this->zp_product_no,true);
		$criteria->compare('zp_saleprice',$this->zp_saleprice);
		$criteria->compare('zp_costprice',$this->zp_costprice);
		$criteria->compare('zp_fx_price',$this->zp_fx_price);
		$criteria->compare('zp_fx_saleprice',$this->zp_fx_saleprice);
		$criteria->compare('zp_inventory',$this->zp_inventory);
		$criteria->compare('zp_sale_num',$this->zp_sale_num);
		$criteria->compare('zp_tax',$this->zp_tax);
		$criteria->compare('zp_weight',$this->zp_weight);
		$criteria->compare('zp_units',$this->zp_units,true);
		$criteria->compare('zp_pic',$this->zp_pic,true);
		$criteria->compare('zp_status',$this->zp_status);
		$criteria->compare('zp_nostatus',$this->zp_nostatus,true);
		$criteria->compare('zp_state',$this->zp_state);
		$criteria->compare('zp_draft',$this->zp_draft);
		$criteria->compare('zp_new',$this->zp_new);
		$criteria->compare('zp_point',$this->zp_point);
		$criteria->compare('zt_ids',$this->zt_ids,true);
		$criteria->compare('zp_hits',$this->zp_hits);
		$criteria->compare('zp_fav_num',$this->zp_fav_num);
		$criteria->compare('zp_commend',$this->zp_commend);
		$criteria->compare('zp_fenxiao',$this->zp_fenxiao);
		$criteria->compare('zp_repair',$this->zp_repair);
		$criteria->compare('zp_guarantee',$this->zp_guarantee);
		$criteria->compare('ze_id',$this->ze_id);
		$criteria->compare('zp_exp_config',$this->zp_exp_config,true);
		$criteria->compare('zbl_id',$this->zbl_id);
		$criteria->compare('inputtime',$this->inputtime);
		$criteria->compare('updatetime',$this->updatetime);
		if($this->min_sale_num) $criteria->compare('zp_sale_num',">=".$this->min_sale_num);
		
		//跟据自定义一级分类查询产品
		if(!empty($this->pro_cat_one)){
			$criteria->join .= ' LEFT JOIN {{cmp_catlog}} ccl ON ccl.zp_id=t.zp_id ';
			$criteria->join .= ' LEFT JOIN {{cmp_cat}} cc ON ccl.zpc_id=cc.zpc_id';
			$criteria->addCondition(" (cc.zpc_id={$this->pro_cat_one} OR cc.zpc_parentid={$this->pro_cat_one}) ");
		}
		//根据货号查询产品
		if(!empty($this->pro_no)){
			$criteria->join .= ' LEFT JOIN {{pro_attribute}} pa ON pa.zp_id=t.zp_id ';
			$criteria->addCondition("pa.zpa_pro_no like '%".$this->pro_no."%'");
		}
		//$criteria->group = 'zp_id';
		if(!empty($this->zp_commend)){
			$pageSize = 7;
		}
		//关键字
		if(!empty($this->keyword)){
			$criteria->addCondition("zp_name like '%".$this->keyword."%'");
		}else{
			$criteria->compare('zp_name',$this->zp_name,true);
			$criteria->compare('zp_content',$this->zp_content,true);
		}
		//行业分类
		if(!empty($this->catgory_id)){
			$criteria->join .= ' LEFT JOIN {{category}} zca ON zca.zca_id=t.zca_id ';
			$criteria->addCondition(" (zca.zca_id={$this->catgory_id} OR zca.zca_parentid={$this->catgory_id} OR zca.zca_topid={$this->catgory_id})");
		}
		//产品属性
		if(!empty($this->att)){
			//获取标识对应的属性
			$attmarkval = AttSelect::model()->getMarkVal($this->att);
			//统计包含所选属性的所有产品ID
			foreach($attmarkval as $val){
				$data = ProAttribute::model()->findAllByAttributes(array('za_title'=>$val['za_title'],'zpa_val'=>$val['zpa_val']));
				$ids[] = CHtml::listData($data,'zp_id','zp_id');
			}
			//取并集
			$attrMum = count($ids);
			$resultids = $ids[0];
			for($i=1;$i<$attrMum;$i++){
				$resultids = array_intersect($resultids, $ids[$i]);
			}
			//查询匹配
			$criteria->addInCondition('zp_id',$resultids);
		}else{
			$criteria->compare('zp_id',$this->zp_id);
		}
		//价格区间
		if(!empty($this->price_level)){
			if($this->price_level==1){
				$criteria->compare('zp_price','<10');
			}elseif($this->price_level==2){
				$criteria->addBetweenCondition('zp_price',10,50);
			}elseif($this->price_level==3){
				$criteria->addBetweenCondition('zp_price',50,100);
			}elseif($this->price_level==4){
				$criteria->addBetweenCondition('zp_price',100,300);
			}elseif($this->price_level==5){
				$criteria->addBetweenCondition('zp_price',300,500);
			}elseif($this->price_level==6){
				$criteria->compare('zp_price','>500');
			}
		}elseif(empty($this->price_min)&&!empty($this->price_max)){
			$criteria->compare('zp_price',"<".$this->price_max);
		}elseif(!empty($this->price_min)&&empty($this->price_max)){
			$criteria->compare('zp_price',">".$this->price_min);
		}elseif(!empty($this->price_min)&&!empty($this->price_max)){
			$criteria->addBetweenCondition('zp_price',$this->price_min,$this->price_max);
		}else{
			$criteria->compare('zp_price',$this->zp_price);
		}

		if($this->butPromotion){
			$criteria->addNotInCondition('zp_id',$this->findAllActivityPro()); 
		}

		//排序
		if($this->list_order==1){
			//时间倒序，默认
			$criteria->order = 'inputtime DESC';
		}elseif($this->list_order==2){
			//销量倒序
			$criteria->order = 'zp_sale_num DESC';
		}elseif($this->list_order==3){
			//点击量倒序
			$criteria->order = 'zp_hits DESC, inputtime DESC';
		}elseif($this->list_order==4){
			//价格升序
			$criteria->order = 'zp_price ASC';
		}elseif($this->list_order==5){
			//销量升序
			$criteria->order = 'zp_sale_num ASC';
		}elseif($this->list_order==6){
			//价格倒序
			$criteria->order = 'zp_price DESC';
		}elseif($this->list_order==7){
			//时间升序
			$criteria->order = 'inputtime ASC';
		}else{
			//时间倒序，默认
			$criteria->order = 'inputtime DESC';
		}
		
		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
			'pagination'=>array('pageSize'=>$pageSize),
		));
	}
	
	public function recycleSearch()
	{
		$criteria=new CDbCriteria;
		$time = time()-3600*24*30*6;
		$criteria->compare('updatetime','<'.$time);
		$criteria->compare('zp_state',$this->zp_state);
	
		return new CActiveDataProvider($this, array(
				'criteria'=>$criteria,
				//'pagination'=>array('pageSize'=>3),
		));
	}
	//推荐位可推荐的数据列表
	public function recommendSearch()
	{
		$criteria=new CDbCriteria;
		$criteria->order = 'inputtime DESC';
		$criteria->compare('zp_state',2);
		$criteria->compare('zp_status',2);
	
		return new CActiveDataProvider($this, array(
				'criteria'=>$criteria,
		));
	}
	
	public function getColor($type=null){
		if($type==null){
			return 	array(
				'军绿色'=>'style="background-color:#5d762a"',
				'天蓝色'=>'style="background-color:#1eddff"',
			  '巧克力色'=>'style="background-color:#d2691e"',
				  '桔色'=>'style="background-color:#ffa500"',
				'浅灰色'=>'style="background-color:#e4e4e4"',
				'浅绿色'=>'style="background-color:#98fb98"',
				'浅黄色'=>'style="background-color:#ffffb1"',
			'深卡其布色'=>'style="background-color:#bdb76b"',
				'深灰色'=>'style="background-color:#666"',
				'深紫色'=>'style="background-color:#4b0082"',
				'深蓝色'=>'style="background-color:#dda0dd"',
				  '白色'=>'style="background-color:#fff"',
				'粉红色'=>'style="background-color:#ffb6c1"',
				'紫罗兰'=>'style="background-color:#dda0dd"',
				  '紫色'=>'style="background-color:#800080"',
			   	  '红色'=>'style="background-color:#ff0000"',
				  '绿色'=>'style="background-color:#008000"',
				  '花色'=>'style="background: url(\'/css/style/img/color_lump.png\') no-repeat scroll 0 0 transparent;"',
				  '蓝色'=>'style="background-color:#0000ff"',
				  '褐色'=>'style="background-color:#855b00"',
				  '透明'=>'style="background: url(\'/css/style/img/color_lump.png\') no-repeat scroll 0 0 transparent;background-position: 0px -14px;"',
				'酒红色'=>'style="background-color:#990000"',
				  '黄色'=>'style="background-color:#ffff00"',
				  '黑色'=>'style="background-color:#000000"',
			);
		}else{
			$level = $this->getColor();
			if(array_key_exists($type,$level)){
				return $level[$type];
			}
		}
	}
	/*
	 * 运费模式
	 * */
	public function getExpStatus($type=null){
		if($type==null){
			return array(
				'1'=>'卖家承担运费',
				'2'=>'买家承担运费',		
			);
		}else{
			$level = $this->getExpStatus();
			return $level[$type];
		}
	}
	
	public function beforeSave(){
		if(parent::beforeSave()){
			if($this->isNewRecord){
				//公司ID
				$this->zm_id = Company::model()->getCmpUserId();
				if($this->zm_id==0){
					//产品审核状态
					$this->zp_status = '2';
				}else{
					//产品审核状态,获取系统配置值，为2不用审核，1需要审核
					$this->zp_status = F::setting('CmpNewProductStatus');
				}
				//是否上架
				$this->zp_state = '2';
				//发布时间,若为空，则发布时间为当前时间
				$this->zp_draft = empty($this->zp_draft)?time():$this->zp_draft;
				//创建时间
				$this->inputtime = time();
				return true;
			}else{
				$this->updatetime = time();
				return true;
			}
		}else{
			return false;
		}
	}
	/* 查询商家的产品
	 * $zp_status 状态1审核中,2通过,3未通过
	* $zp_state 是否上架:1否2是3逻辑删除
	* $zp_new 是否新产品1否2是
	* $zp_commend 商铺产品推荐:1否2是
	* */
	public function getProBycom($zp_status='',$zp_state='2',$zp_new='1',$zp_commend='',$order='inputtime desc'){
		$criteria = new CDbCriteria();
		$criteria->compare('zm_id',Yii::app()->user->userid);
		if(isset($zp_status)){
			$criteria->compare('zp_status', $zp_status);
		}
		if(isset($zp_commend)){
			$criteria->compare('zp_commend', $zp_commend);
		}
		$criteria->compare('zp_state', $zp_state);
		$criteria->compare('zp_new', $zp_new);
		$criteria->order = $order;
		// 		$count = Product::model()->count($criteria);
		// 		$pager = new CPagination($count);
		// 		$pager->pageSize = $page;
		// 		$pager->applyLimit($criteria);
		return new CActiveDataProvider($this, array(
				'criteria'=>$criteria,
				'pagination'=>array('pageSize'=>5),
		));
	}
	/* 更改商家产品的推荐状态
	 * $zp_commend 是否推荐
	* $zp_id 产品id
	* */
	public function updateComCommend($zp_id,$cp_commend){
		$userid  = Yii::app()->user->userid;
		if(isset($zp_id)){
			if(is_array($zp_id)){
				$zp_ids = implode(',',$zp_id);
				self::model()->updateAll(array ('zp_commend' => $cp_commend),'zp_id in('.$zp_ids.') and zm_id='.$userid);
			}else{
				self::model()->updateAll(array('zp_commend'=>$cp_commend),'zp_id ='.$zp_id.' and zm_id='.$userid);
			}
		}else{
			return false;
		}
		return true;
	}
	/*产品上下架
	 * $zp_id array 产品id
	* $zp_state 更新的状态 */
	public function productDown($zp_ids,$zp_state){
		if(isset($zp_ids)){
			if(is_array($zp_ids)){
				foreach($zp_ids as $zp_id){
					$this->productDown($zp_id,$zp_state);
				}
			}else{
				if($zp_state==1){
					//下架更新状态
					self::model()->updateAll(array('zp_state'=>1),'zp_id ='.$zp_ids.' and zm_id='.Yii::app()->user->userid);
					//查询是否有活动，有就删除
					$tuan = ProTuan::model()->findByAttributes(array('zp_id'=>$zp_ids));
					if(isset($tuan->zpt_id)){
						ProTuan::model()->deleteByPk($tuan->zpt_id);//执行删除
					}
				}else{
					//上架
					self::model()->updateAll(array('zp_state'=>2,'zp_status'=>1),'zp_id ='.$zp_ids.' and zm_id='.Yii::app()->user->userid);
				}
			}
			return true;
		}
	}
	/**
	 * 逻辑删除
	 * @return array 返回删除失败ID
	 */
	public function deleteOnLogic($id)
	{
		$id = $id === null ? $this->zp_id :$id;
		static $failedIds;
		if(is_array($id)){
			foreach($id as $ids){
				$this->deleteOnLogic($ids);
			}
		}else{
			$model = $this->findByPk($id);
			if($model->zp_state != 1){//是否已经下架
				$failedIds[] = $id;
			}
			$model->zp_state = 3;
			$model->update();
			return $failedIds;
		}
	}
	
	/**
	 * 手动物理删除
	 * @return array 返回删除失败ID
	 */
	public function deleteByHand($id=null)
	{
		$id = !$id ? $this->zp_id :$id;
		if(!$id) return ;
		static $failedIds;
		if(is_array($id)){
			foreach($id as $ids){
				$this->deleteByHand($ids);
			}
		}else{
			if(!$this->isLogicDelete($id)){//是否已被逻辑删除
				$failedIds['notDelete'][] = $id;
			}elseif($this->hasDealingReport($id)){//是否存在为解决的举报或维权
				$failedIds['dispute'][] = $id;
			}elseif(!$this->sleepForSix($id)){//是否已经六个月以上未更新
				$failedIds['time'][] = $id;
			}else{//执行物理删除
				$this->deleteOnDisk($id);
			}
			return $failedIds;
		}
	}
	
	/**
	 * 自动物理删除，系统自动进行删除时调用
	 * @return array
	 */
	public function deleteBySystem()
	{
		$time = time()-3600*24*30*6;
		$sql = 'SELECT p.zp_id,r.zmr_status AS status FROM zd_product p LEFT JOIN zd_mem_report r ON p.zp_id=r.zp_id WHERE p.zp_state=3 AND p.updatetime<'.$time;
		$ids = Yii::app()->db->createCommand($sql)->queryAll();
		foreach ($ids as $id){
			if($id['status'] != 1 && $id['status'] != 2){
				//执行逻辑删除
				$this->deleteOnDisk($id['zp_id']);
			}
		}
	}
	
	/**
	 * 执行物理删除
	 * @return array customized attribute labels (name=>label)
	 */
	public function deleteOnDisk($id)
	{
		$id = $id === null ? $this->zp_id :$id;
		if(is_array($id)){
			foreach($id as $ids){
				$this->deleteOnDisk($ids);
			}
		}else{
			//删除产品相关信息
			ProImages::model()->deleteAllByAttributes(array('zp_id'=>$id));//产品图片关系
			ProUptimelog::model()->deleteAllByAttributes(array('zp_id'=>$id));//上下架记录
			ProSpe::model()->deleteAllByAttributes(array('zp_id'=>$id));//规格组-价格
			ProAttribute::model()->deleteAllByAttributes(array('zp_id'=>$id));//规格组-库存
			ProTuan::model()->deleteAllByAttributes(array('zp_id'=>$id));//团购秒杀
			ProDiscount::model()->deleteAllByAttributes(array('zp_id'=>$id));//限时打折
			Product::model()->deleteByPk($id);//产品信息
			return true;
		}
	}
	
	/**
	 * 查询产品上下架状态
	 * @param $id 产品ID
	 * @return $state：1否2是3逻辑删除
	 */
	public function getStateById($id)
	{
		$state = Yii::app()->db->createCommand('SELECT zp_state FROM {{product}} WHERE zp_id='.$id)->queryColumn();
		return $state ? $state[0] : null;
	}
	
	/**
	 * 查询产品是否已逻辑删除
	 * @param $id 产品ID
	 * @return boolen
	 */
	public function isLogicDelete($id)
	{
		return $this->getStateById($id)==3 ? true : false;
	}
	
	/**
	 * 查询产品是否存在未解决的纠纷
	 * @param $id 产品ID
	 * @return boolen
	 */
	public function hasDealingReport($id)
	{
		$model = MemReport::model()->findByAttributes(array('zp_id'=>$id),'zmr_status in(1,2)');
		if($model)
			return true;
		return false;
	}
	
	/**
	 * 查询产品是否已六个月未更新
	 * @param $id 产品ID
	 * @return boolen
	 */
	public function sleepForSix($id)
	{
		$uptime = Yii::app()->db->createCommand('SELECT updatetime FROM {{product}} WHERE zp_id='.$id)->queryColumn();
		return $uptime && $uptime[0] < time()-3600*24*30*6 ? true : false ;
	}
	
	/**查看产品详细
	 *   */
	public function GetInfoByid($id){
		$productinfo = self::model()->find('zp_id='.$id);
		if(!empty($productinfo)){
			$productinfo = $productinfo->attributes;
		}else{
			//throw new CHttpException('没有相关信息');
			echo '没有相关信息';
		}
		$category = new Category();
		$category = $category->findByPk($productinfo['zca_id']);
		if(!empty($productinfo)){
			//产品所属的上一级分类
			$productinfo['catparentid'] = $category->attributes['zca_parentid'];
			//产品所属的顶级分类
			$productinfo['cattopid']    = $category->attributes['zca_topid'];
		}

		//取产品规格
		$pro_attribute = Yii::app()->db->createCommand('SELECT * FROM {{pro_attribute}} WHERE zp_id = '.$id.' AND zpa_type=2 ORDER BY zpa_id ASC')->queryAll();
		//取产品属性
		$pro_atts = Yii::app()->db->createCommand('SELECT * FROM {{pro_attribute}} WHERE zp_id = '.$id.' AND zpa_type=1')->queryAll();
		
		//取当前分类的所有属性出来
		$Attsql = new CDbCriteria();
		$Attsql->select ='za_id,za_title';
		$Attsql->compare('zca_id', $productinfo['zca_id']);
		$Attsql->compare('za_type', 1);
		$Attsql->order = 'za_listorder ASC';
		$attribute = Attribute::model()->findAll($Attsql);
		//print_r($attribute);
		//取产品图片
		$productinfo['imgs'] = Yii::app()->db->createCommand('SELECT * FROM {{pro_images}} WHERE zp_id = '.$id.' ORDER BY zpg_id ASC ')->queryAll();
		//总评数
		$productinfo['commenttotal'] = count(OrdComment::model()->findAll('zoc_type =2 AND zp_id='.$id));
		//好评数
		$productinfo['goodcomment'] = count(OrdComment::model()->findAll('zoc_type =2 AND zoc_sum = 3 AND zp_id='.$id));
		//中评数
		$productinfo['centrecomment'] = count(OrdComment::model()->findAll('zoc_type =2 AND zoc_sum = 2 AND zp_id='.$id));
		//差评
		$productinfo['negativecomment'] = count(OrdComment::model()->findAll('zoc_type =2 AND zoc_sum = 1 AND zp_id='.$id));

		if($pro_attribute){
			foreach($pro_attribute as $key=>$val){	
				  $productinfo['spe'][$val['za_id']]['za_id']=$val['za_id'];
				  $za_title = Attribute::model()->findByAttributes(array('za_id'=>$val['za_id']));
				  if(!empty($za_title)){
				  	$productinfo['spe'][$val['za_id']]['za_title']=$za_title->attributes['za_title'];
				  }
				  $productinfo['spe'][$val['za_id']]['zpa_val'][]=$val;
				  $productinfo['spe'][$val['za_id']]['zps_photo']=$val['zps_photo'];		
			}
		}else{
			$productinfo['spe'] = array();
		}

		
		foreach ($attribute as $k => $v) {			  //将属性信息写入产品信息
			foreach($pro_atts as $key=>$val){
					  
					  $productinfo['att'][$v['za_id']]['za_id']=$v['za_id'];   //	属性ID	  
					  
					  $productinfo['att'][$v['za_id']]['za_title']=$v['za_title']; //属性名称
					  
					  if( $v['za_id'] == $val['za_id'] )
					  {
						  	if(isset($productinfo['att'][$v['za_id']]['zpa_val'])){
						  		$productinfo['att'][$v['za_id']]['zpa_val'] .= $val['zpa_val'].' '; //连接属性值
						  	}else{
						  		$productinfo['att'][$v['za_id']]['zpa_val'] = $val['zpa_val'].' '; //连接属性值
						  	}
					  }
					  
			}		   
		}
		return $productinfo;
	}

	/**
	 *根据会员id获取公司最新产品
	 * @param $amount 条数
	 * @param $days 天数
	 * @return array
	 */
	public function getNewProductByMemberId($memberid, $amount=5, $days=15){
		$criteria = new CDbCriteria();
		$time = time()-$days*3600*24;
		$criteria->compare('inputtime', '>'.$time);
		$criteria->compare('zp_status', 2);
		$criteria->compare('zp_state', 2);
		$criteria->order = 'zp_id desc';
		$criteria->limit = $amount;
		return $this->findAll($criteria);
	}
	
	/**
	 * 根据产品id建立产品链接
	 * @param $productid 产品ID 
	 * @param $options  CHtml LINKHTML参数  
	*/
	public static function createProductLink($productid, $options=array()){
		$criteria = new CDbCriteria();
		$criteria->select = 'zp_id,zp_name';
		$criteria->compare('zp_id',$productid);
		$model = Product::model()->find($criteria);
		return CHtml::link($model->zp_name, Yii::app()->createUrl('home/product/detail',array('id'=>$model->zp_id)), $options);		
	}

	/**
	 * 取产品标题链接
	 */
    public function getTitle() {
        return CHtml::link($this->zp_name, array('/home/product/detail', 'id' => $this->zp_id), array('zp_name' => $this->zp_name));
    }

    public function getBtnList() {
        return CHtml::textField('qty', $this->min_number, array('size' => '2', 'maxlength' => '5', 'id' => 'qty_' . $this->zp_id)) . '&nbsp;'
                . CHtml::link(CHtml::image(Yii::app()->request->baseUrl . '/images/btn_buy.gif'), '#', array('id' => 'btn-buy-' . $this->zp_id, 'onclick' => 'fastBuy(this, ' . $this->zp_id . ', $("#qty_' . $this->zp_id . '").val())'
                ))
                . '&nbsp;' . CHtml::link(CHtml::image(Yii::app()->request->baseUrl . '/images/btn_addwish.gif'), '#', array('id' => 'btn-addwish-' . $this->zp_id, 'onclick' => 'addWish(this, ' . $this->zp_id . ')'
                        ));
    }

     public function getThumb($type = 'small') {
        $img = $this->zp_pic;
        $trueimage = Yii::app()->request->hostInfo . $img;
        //if (Tool::isfile($trueimage)) {
        //$img_thumb = Yii::app()->request->baseUrl . ImageHelper::thumb($width, $height, $img, array('method' => 'resize'));
        if ($type == 'big' ) {
        	$width = '600';
        }elseif( $type == 'list'){
        	$width = '310';
        }else{
        	$width = '100';
        }
        $pathinfo  = pathinfo($img);
        $img_thumb = $pathinfo['dirname'] . '/' .$pathinfo['filename'] . '_' . $width .'.' . $pathinfo['extension'];
        $img_thumb_now = CHtml::image($img_thumb, $this->zp_name);
        return CHtml::link($img_thumb_now, array('/home/product/detail', 'id' => $this->zp_id), array('zp_name' => $this->zp_name));
        //}else{
        //    return '没有图片';
        //}
    }

    /**
     * 获取搜索类型
     */
    public function getSearchType($type=null){
    	if($type==null){
    		return array(
    			'1'=>'根据产品名称',
    			'2'=>'根据商家名称',
    		);
    	}
    }
	
    /**
     * 查找后的操作
     */
    protected function afterFind(){
    	if(!empty($this->spec)){
    		foreach($this->spec as $spec){
    			if(empty($this->pro_no)){
    				$this->pro_no = $spec->zpa_pro_no;
    			}else{
    				$this->pro_no .= ','.$spec->zpa_pro_no;
    			}
    		}
    	}
    	return true;
    }

    /**
	 * 根据资讯条件获取相应内容
	 * $condition 条件
	 * $limit 返回几条数据
	 * @return Array
	 */
	public function getProductData($condition, $limit='', $offset='', $order='zp_id DESC')
	{
		return Product::model()->findAll(array('condition'=>$condition,'order'=>$order, 'limit'=>$limit, 'offset'=>$offset));
	}
	
	/**
	 * 更新其它表记录的该产品图片信息目标
	 */
	public function updateRelatePic($preimg,$targetimg){
		//更新产品推荐记录的产品图片
		$criteria=new CDbCriteria;
		$criteria->compare('zpl_pic', $preimg);
		$set = array('zpl_pic'=>$targetimg);
		PosLog::model()->updateAll($set,$criteria);
		
		//更新团购记录信息表
		$criteria=new CDbCriteria;
		$criteria->compare('zpt_pic', $preimg);
		$set = array('zpt_pic'=>$targetimg);
		ProTuan::model()->updateAll($set,$criteria);
		
		//如还有其它要修改的数据在些添加。。
	}
	
	/**
	 *@查询所有已参加限时折扣、团购活动、抢购秒杀,且活动还未被关闭或删除，的产品
	 *@return array
	 */
	public function findAllActivityPro($order='inputtime desc'){
		$discountArr = ProDiscount::model()->findAll("`zpd_status`='1'",array('order'=>$order),array());
		$tuanArr = ProTuan::model()->findAll("`zpt_close`='1'",array('order'=>$order));
		$activityArr = array();
		foreach($discountArr as $val){
			$activityArr[] = $val[zp_id]; 
		}
		foreach($tuanArr as $val){
			$activityArr[] = $val[zp_id]; 
		}
		return $activityArr;
	}

}